package com.example.blog.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @Classname MailUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/7 9:45
 * @Created by wlh12
 */
@Component
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromMail;
    public void sendSimpleMail(String [] toMail,String subject,String content){
        MimeMessage message;
        try {
            message = mailSender.createMimeMessage();
            message.setFrom(fromMail);
            message.setSubject(subject);
            message.setText(content);
            message.setRecipients(Message.RecipientType.TO,toAddress(toMail));
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        mailSender.send(message);
    }

    private Address[] toAddress(String [] toMails) {
        Address[] addresses = new Address[toMails.length];
        for (int i = 0;i< toMails.length;i++) {
            try {
                addresses[i] = new InternetAddress(toMails[i]);
            } catch (AddressException e) {
                throw new RuntimeException(e);
            }
        }
        return addresses;
    }
}
